<?php


namespace plugin\agent\event;


use app\common\service\ConfigService;
use app\model\user\User;
use Exception;
use plugin\agent\app\admin\logic\AgentUserLogic;
use Psr\Log\LoggerInterface;
use support\Log;

class AddAgent
{
    protected LoggerInterface $logger;

    /**
     * 判断是不是人人分销 并且添加分销商
     * @param User $user
     */
    public function execute(User $user)
    {
        $this->logger = Log::channel("agent");
        try {
            $config = ConfigService::getConfig('AGENT_MODEL');
            if ($config['open'] == 0) {
                return;
            }
            $logic = new AgentUserLogic();
            if ($config['type'] == 1) {
                //人人分销
                $logic->addByUser([
                    'user_id' => $user['id']
                ]);
            }

            //判断用户是不是邀请来的 如果是邀请的需要查询邀请人是不是分销商 给绑定分佣的分销商id
            if ($user->invite_id > 0) {
                $agent_id = $logic->where([
                    'user_id' => $user->invite_id
                ])
                    ->value('agent_id');
                User::update([
                    'commission_agent_id' => $agent_id,
                ], [
                    'id' => $user['id'],
                ]);
            }
        } catch (Exception $exception) {
            $this->logger->error("添加分销商异常:" . $exception->getMessage());
        }
    }
}